import axios from "axios";
import qs from "qs";

let baseURL = "http://localhost:3000";
if (process.env.NODE_ENV === "development") {
  // baseURL = 'http://www.hbzhiku.org.cn/';
  // baseURL = "http://localhost:8080/";
  baseURL = "http://www.hbzhiku.org.cn/ts/";
} else if (process.env.NODE_ENV === "production") {
  baseURL = "http://www.hbzhiku.org.cn/ts/";
  // baseURL = 'http://www.yuwubao.cn:8780/'
}

const userId = localStorage.getItem("zhikuFrontUserId") || undefined;

const instance = axios.create({
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    accessToken: localStorage.getItem("zhikuFrontUserToken") || ""
  },
  transformRequest: [
    function(data) {
      let ret = "";
      for (let it in data) {
        ret +=
          encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
      }
      return ret;
    }
  ],
  baseURL,
  timeout: 3000
});

instance.interceptors.request.use(
  config => {
    return config;
  },
  err => Promise.reject(err)
);

instance.interceptors.response.use(res => res, err => Promise.reject(err));

export function get(url, params) {
  const Params = Object.assign({}, params, {
    userId
  });
  return new Promise((resolve, reject) => {
    var Url = "";
    if (Params === null || Params === undefined) {
      Url = url;
    } else {
      Url = url + "?" + qs.stringify(Params);
    }
    instance.get(Url).then(
      res => {
        resolve(res.data);
      },
      err => {
        reject(err);
      }
    );
  });
}
export function post(url, params, opt = {}) {
  const Params = Object.assign(
    {},
    {
      id: userId
    },
    params
  );
  const { headers, data } = opt;
  let transformRequest;
  if (headers && headers["Content-Type"] === "multipart/form-data;") {
    transformRequest = [
      function(data) {
        return data;
      }
    ];
  }
  return new Promise((resolve, reject) => {
    instance
      .request({
        method: "post",
        url,
        params: Params,
        headers: headers || {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        transformRequest,
        data
      })
      .then(
        res => {
          resolve(res.data);
        },
        err => {
          reject(err);
        }
      );
  });
}
